using System;
using System.Text.Json;
using System.Threading.Tasks;
using EasyDapr.Domain;
using EasyDapr.Infrastructure.Response;
using Microsoft.AspNetCore.Http;

namespace EasyDapr.Infrastructure.Middlewares
{
    /// <summary>
    /// 异常处理中间件
    /// </summary>
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;

        public ExceptionHandlingMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// Invoke
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            var isHandled = false;
            try
            {
                await _next(context);
            }
            catch (CoreException ex)
            {
                isHandled = true;
                await HandleExceptionAsync(context, 200, ex.Message);
            }
            catch (ApplicationException ex)
            {
                isHandled = true;
                await HandleExceptionAsync(context, 200, ex.Message);
            }
            catch (ArgumentNullException ex)
            {
                isHandled = true;
                await HandleExceptionAsync(context, 200, ex.Message);
            }
            catch (ArgumentException ex)
            {
                isHandled = true;
                await HandleExceptionAsync(context, 200, ex.Message);
            }
            catch (Exception ex)
            {
                isHandled = true;
                await HandleExceptionAsync(context, 500, ex.Message, ex.InnerException?.Message);
            }
            finally
            {
                if (!isHandled)
                {
                    var message = "";
                    var statusCode = context.Response.StatusCode;
                    switch (statusCode)
                    {
                        case 401:
                            message = "Unauthorized";
                            break;
                        case 404:
                            message = "Not Found";
                            break;
                        case 503:
                            message = "Service Unavailable";
                            break;
                    }

                    await HandleExceptionAsync(context, statusCode, message);
                }
            }
        }

        private static Task HandleExceptionAsync(
            HttpContext context,
            int statusCode,
            string message,
            string innerMessage = null)
        {
            var result = JsonSerializer.Serialize(new ApiResult<string>
            {
                InnerMessage = innerMessage,
                StatusCode = statusCode,
                Message = message,
                Success = false
            });
            context.Response.ContentType = "application/json;charset=utf-8";
            return context.Response.WriteAsync(result);
        }
    }
}